from __future__ import absolute_import, unicode_literals


import os

from celery import Celery, shared_task

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base')


app = Celery('recruitment')


from django.conf import settings

BASE_DIR = settings.BASE_DIR
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.


class CeleryConfig:
    CELERY_BROKER_URL = 'redis://127.0.0.1:6379/14'
    CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/15'
    CELERY_ACCEPT_CONTENT = ['application/json']
    CELERY_RESULT_SERIALIZER = 'json'
    CELERY_TASK_SERIALIZER = 'json'
    CELERY_TIMEZONE = 'Asia/Shanghai'
    CELERYD_MAX_TASKS_PER_CHILD = 10
    CELERYD_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_work.log")
    CELERYBEAT_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_beat.log")


# app.config_from_object('django.conf:settings', namespace='CELERY')
app.config_from_object(CeleryConfig, namespace='CELERY')
#
# # Load task modules from all registered Django app configs.
app.autodiscover_tasks()
#
#
@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


# app = Celery('tasks', backend='redis://127.0.0.1/3', broker='redis://127.0.0.1/4')
from celery.schedules import crontab

# this is important to load the celery tasks
from recruitment.tasks import add

app.conf.beat_schedule = {
    'add-every-10-seconds': {
        'task': 'recruitment.tasks.add',
        'schedule': 10.0,
        'args': (16, 4, )
    },
}

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls test('hello') every 10 seconds.
    sender.add_periodic_task(10.0, test.s('hello'), name='hello every 10')

    # Calls test('world') every 30 seconds
    sender.add_periodic_task(30.0, test.s('world'), expires=10)

    # Executes every Monday morning at 7:30 a.m.
    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )


@app.task
def test(arg):
    print(arg)


app.conf.timezone = "Asia/Shanghai"